import itertools

from fastapi import APIRouter, Depends
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session

from common.database import get_db
from common.redispy import redispy
from core.response import resp_login, resp_401, resp_200
from app.login.schemas import Token
from app.login.handle import verity_user
from core.security import security, token_checker, oauth2_scheme
from app.auth.models import AuthUsers

router = APIRouter()


@router.post("/login", summary="用户登录", description="用户登录校验获取令牌信息", response_model=Token)
def login_for_access_token(db: Session = Depends(get_db), form: OAuth2PasswordRequestForm = Depends()):
    user = verity_user(db, username=form.username, password=form.password)
    if not user:
        return resp_401(message="Incorrect username password or Inactive user")
    access_token = security.create_access_token(data=user)
    return resp_login(access_token)


@router.post("/logout", summary="用户登出", description="清理用户令牌信息")
def logout_for_access_token(user=Depends(token_checker), token: str = Depends(oauth2_scheme)):
    redispy.delete_token(user["username"], token)
    return resp_200()



@router.get("/user/info", summary="用户前端展示", description="用户前端侧边栏可展示列表信息")
def user_info(db: Session = Depends(get_db), user=Depends(token_checker)):
    data = AuthUsers.get_permissions_tags_by_uuid(db, user.get("uuid"))
    # https://blog.csdn.net/pythonxuexi123/article/details/112987226
    tag_list = list(itertools.chain(*data)) if list(itertools.chain(*data)) else ['guest']
    return resp_200({'username': user.get("username"), 'avatar': user.get("avatar"), 'roles': tag_list})
